<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a href="javascript:;" :class="{active:articleParams.sorter==='weight_desc'}" @click="change('weight_desc')">推荐</a>
      <a href="javascript:;" :class="{active:articleParams.sorter!=='weight_desc'}" @click="change()">最新</a>
      <div class="logo"><img src="@/assets/logo.png" alt="" /></div>
    </nav>

    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <ArticleItem
        v-for="item in rows"
        :key="item.id"
        :item="item"
        @click.native="$router.push(`/detail?id=${item.id}`)"
      ></ArticleItem>
    </van-list>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
export default {
  name: 'article-page',
  created () {
    // this.getArticles()
  },
  data () {
    return {
      rows: [],
      articleParams: {
        current: 1, // 默认拿第1页数据
        pageSize: 10, // 每页拿10条数据
        sorter: 'weight_desc'// 代表的是推荐 如果不传或值是空是最新的
      },
      loading: false,
      finished: false
    }
  },
  methods: {
    async getArticles () {
      const res = await getArticles(this.articleParams)
      console.log(res)
      // 判断是否到最后一页
      if (res.data?.rows?.length === 0) {
        this.finished = true
        return
      }
      this.rows.push(...res.data.rows)// 把新的10条追加原始上面
      this.loading = false// 在这一行才能保证上一次全部加载结束
      this.articleParams.current++
    },
    onLoad () {
      this.getArticles()
    },
    change (sorter) {
      this.articleParams.sorter = sorter
      this.rows = []// 把列表清空一下
      this.articleParams.current = 1// 把页码值改成1
      this.loading = true// loading为true，表示正在发送异步请求，此时不会触发load事件 也就是不会导致数据有重复的
      this.finished = false// 为了防止推荐已经把数据拉到最后一页 导致finished变成true，上拉加载更多就直接不会再有效果，这块变成false 重新打开这个效果
      this.onLoad()
    }
  }
}
</script>

<style lang="less" scoped>
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;
  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;
    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;
      &::after {
        content: "";
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }
      &.active {
        color: #222;
        &::after {
          width: 14px;
        }
      }
    }
    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}
</style>
